package com.poly.common.core.web.page;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.poly.common.core.tools.utils.Func;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
public class Pagination<T> extends SimplePage<T> implements Serializable {

    private static final long serialVersionUID = 1L;


    public Pagination() {

    }

    public Pagination(IPage page, Integer pageNum, Integer pageSize) {
        setTotal(page.getTotal());
        setRows(page.getRecords());
    }

    public Pagination(long total, List<T> rows) {
        super(total,rows);
    }

    public <C> Pagination<C> toPage(Class<C> targetClazz) {
        Pagination<C> page = new Pagination<>();
        if (Func.isNotEmpty(rows)) {
            List<C> outList = new ArrayList<>(rows.size());
            for (Object source : rows) {
                if (source == null) {
                    continue;
                }
                C bean = BeanUtil.copyProperties(source, targetClazz);
                outList.add(bean);
            }
            page.setRows(outList);
            page.setTotal(getTotal());
        }
        return page;
    }

    public static <C> Pagination<C> toPagination(IPage page, Class<C> targetClazz) {
        Pagination<C> pagination = new Pagination<>();
        if (Func.isNotEmpty(page.getRecords())) {
            List<C> outList = new ArrayList<>(page.getRecords().size());
            for (Object source : page.getRecords()) {
                if (source == null) {
                    continue;
                }
                C bean = BeanUtil.copyProperties(source, targetClazz);
                outList.add(bean);
            }
            pagination.setRows(outList);
            pagination.setTotal(page.getTotal());
        }
        return pagination;
    }



    /**
     * 内存分页
     *
     * @author xubing
     * @updateTime 2023/7/12 10:00
     */
    public Pagination(Integer pageNum, Integer pageSize, List<T> list) {
        setTotal(Long.valueOf(list.size()));
        setRows(list);
        if (list.size() > 0) {
            Integer start = (pageNum - 1) * pageSize;
            Integer end = start + pageSize > list.size() ? list.size() : start + pageSize;
            List<T> pageList = list.subList(start, end);
            setRows(pageList);
        }
    }

}
